package com.runccyy.web;


import com.runccyy.utils.RedisUtil;
import com.runccyy.utils.WeChatUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/wechat")
@Api(value = "wechat", description = "微信相关操作")
public class WeChatController {


    @Resource
    private RedisUtil redisUtil;

    /**
     * 解密微信加密数据接口
     *
     * @param encryptedData 加密数据
     * @param iv            初始向量
     * @return 解密后的数据
     */
    @GetMapping("/decrypt")
    @ApiOperation(value = "decrypt", notes = "加密数据解密")
    public String decryptData(
            @ApiParam(value = "encryptedData", required = true) @RequestParam("encryptedData") String encryptedData,
            @ApiParam(value = "iv", required = true) @RequestParam("iv") String iv,
            @ApiParam(value = "鉴权信息", required = true)@RequestHeader String auth) {
        String string = redisUtil.get(auth).toString();
        String sessionKey = getSessionKey(string);
        return WeChatUtil.decryptData(encryptedData, sessionKey, iv);
    }


    private String getSessionKey(String auth){
        if (auth == null){
            return null;
        }
        String[] parts = auth.split("@k");
        if (parts.length > 1) {
            return parts[1];
        } else {
            return null;
        }

    }
}